﻿using guidHelper;
using Newtonsoft.Json;
using System.Net.Http.Headers;

namespace MyDapperApi.Services.BaiLianAI;

public class BaiLianAIBaseService : IBaiLianAIBaseService
{
    private readonly IConfiguration _configuration;
    private readonly IDateBaseService _dateBaseService;
    private readonly IHttpClientFactory _httpClientFactory;

    public BaiLianAIBaseService(IConfiguration configuration, IDateBaseService dateBaseService, IHttpClientFactory httpClientFactory)
    {
        _configuration = configuration;
        _dateBaseService = dateBaseService;
        _httpClientFactory = httpClientFactory;
    }

    /// <summary>
    /// 阿里云百炼标准 Post 请求
    /// </summary>
    /// <param name="requestContent">包含 JSON 请求体的 StringContent</param>
    /// <param name="url">API 接口地址，例如：https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions</param>
    /// <param name="apiKey">您的百炼 API Key</param>
    /// <returns>反序列化后的百炼 API 响应对象</returns>
    public async Task<DashScopeCompletionResponse> BailianApiPost(StringContent requestContent,string url,string apiKey)
    {
        var client = _httpClientFactory.CreateClient();
        // 💡 增加超时时间到 5 分钟 (300秒)
        client.Timeout = TimeSpan.FromSeconds(300);
        //  设置认证头：使用 API Key 作为 Bearer Token
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", apiKey);

        HttpResponseMessage response = new HttpResponseMessage();

        try
        {
            response = await client.PostAsync(url, requestContent);

            // 关键改变：直接读取为字符串，无需 Stream
            string responseString = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                // 直接反序列化字符串
                var bailianResponse = JsonConvert.DeserializeObject<DashScopeCompletionResponse>(responseString);
                return bailianResponse;
            }
            else
            {
                // 确保打印出 API 错误详情 (responseString 包含了 400 错误的 JSON 内容)
                Console.WriteLine($"[API ERROR] Status: {response.StatusCode}. Content: {responseString}");
                throw new HttpRequestException($"API request failed. Details: {responseString}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[Error] Bailian API Call Exception: {ex.Message}");
            // 建议在这里记录日志
            return null; // 或者返回一个表示失败的默认对象
        }
    }


    // ------------------- 请求和响应中使用的 Message 结构 -------------------
    public class Message
    {
        [JsonProperty("role")]
        public string Role { get; set; } = string.Empty;

        [JsonProperty("content")]
        public string Content { get; set; } = string.Empty;
    }

    // ------------------- 响应中的 Choice 结构 -------------------
    public class Choice
    {
        [JsonProperty("message")]
        public Message Message { get; set; } = new Message();

        [JsonProperty("finish_reason")]
        public string FinishReason { get; set; } = string.Empty;
    }

    // ------------------- 响应中的 Output 结构 -------------------
    public class Output
    {
        [JsonProperty("choices")]
        public List<Choice> Choices { get; set; } = new List<Choice>();

        [JsonProperty("text")] // 兼容部分非Chat API
        public string Text { get; set; } = string.Empty;
    }

    // ------------------- 响应中的 Usage 结构 -------------------
    public class Usage
    {
        [JsonProperty("input_tokens")]
        public int InputTokens { get; set; } = 0;

        [JsonProperty("output_tokens")]
        public int OutputTokens { get; set; } = 0;

        [JsonProperty("total_tokens")]
        public int TotalTokens { get; set; } = 0;
    }

    // ------------------- 完整的 DashScope API 响应结构 -------------------
    public class DashScopeCompletionResponse
    {
        [JsonProperty("request_id")]
        public string RequestId { get; set; } = string.Empty;

        [JsonProperty("output")]
        public Output Output { get; set; } = new Output();

        [JsonProperty("usage")]
        public Usage Usage { get; set; } = new Usage();

        // 错误信息（如果请求失败，但返回了JSON）
        [JsonProperty("code")]
        public string Code { get; set; } = string.Empty;

        [JsonProperty("message")]
        public string ErrorMessage { get; set; } = string.Empty;
    }
}